﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GradeBook.Models;

namespace GradeBook.Daos
{
    public class GroupDao
    {
        
        public static List<Group> Load()
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return db.Group.ToList();
        }

        public static List<Group> LoadByUserId(int userId)
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return (
                    from g in db.Group
                    from rug in db.RelUserGroup
                    where rug.UserId == userId
                    where rug.GroupId == g.Id
                    select g).ToList();
        }

        public static Group GetById(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return db.Group.FirstOrDefault(g => g.Id == id);
        }

        public static void Add(Group group)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Group.AddObject(group);
                db.SaveChanges();
            }
        }
        public static void Update(Group group)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Group.ApplyCurrentValues(group);
                db.SaveChanges();
            }
        }
        public  static void Remove(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Group.DeleteObject(db.Group.FirstOrDefault(g=> g.Id == id));
                db.SaveChanges();
            }
        }
    }
}